﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace nanoCMS.Core.WebProviders {
	public class NcAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter  {

		public new string Users { get; set; }
		public new string Roles { get; set; }

		protected new bool AuthorizeCore(HttpContextBase httpContext) {
			if (httpContext == null) throw new ArgumentNullException("httpContext");

			if (!SessionManagerBase.IsAuthenticated) return false;

			//todo: add roles and etc
			return true;
		}


		//private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) {
		//   validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
		//}


		public override void OnAuthorization(AuthorizationContext filterContext) {
			if (filterContext == null) throw new ArgumentNullException();

			if (AuthorizeCore(filterContext.HttpContext)) {
				//TODO: ugraditi zastitu od cacha
				// ** IMPORTANT **
				// Since we're performing authorization at the action level, the authorization code runs
				// after the output caching module. In the worst case this could allow an authorized user
				// to cause the page to be cached, then an unauthorized user would later be served the
				// cached page. We work around this by telling proxies not to cache the sensitive page,
				// then we hook our custom authorization code into the caching mechanism so that we have
				// the final say on whether a page should be served from the cache.


				//HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
				//cachePolicy.SetProxyMaxAge(new TimeSpan(0));
				//cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
			} else {
				filterContext.Result = new HttpUnauthorizedResult();
				filterContext.HttpContext.Response.StatusCode = 401;
				RequestItems.Redirect = HtmlHelpers.LinkHelper.Url(filterContext.RequestContext, "LogIn").ToString();
				filterContext.HttpContext.Response.Write("");

			}
		}
	}
}
